//
//  Index_StaicViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/2.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "Index_StaicViewController.h"
#import "Index_LIiveCell.h"
#import "StaicShow_Cell.h"
#import "Staic_TopCell.h"
#import "LiveCatogryViewController.h"
#import "Static_ShowCell.h"
#import "LiveDetailssViewController.h"
#import "OYCountDownManager.h"
#import "StaticPopViewController.h"
#import "ShowDetail.h"
#import "PlayViewController.h"
#import "HomeViewController.h"
#import "AreaViewController.h"
#import "LiveModel.h"
#import "Regist2ViewController.h"
#import "WXApi.h"
#import "C_PlayViewController.h"
#import "SPRollView.h"
#import "NSDate+Helen.h"
@interface Index_StaicViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate>
//@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(assign)CGFloat oldTopHeight;
@property(assign)CGFloat oldTabHeight;
@property(nonatomic,strong)NSMutableArray *dataSouce;
@property (nonatomic ,strong)dispatch_source_t Dm_timer;
@property(nonatomic,strong)NSString *keywords;
@property(assign)NSInteger pageIndex;
@property(nonatomic,strong)NSString *now_time;
@property(nonatomic,strong)NSDictionary *StaticshowDic;
@property(nonatomic,strong)Staic_TopCell *Topcell;
@property(nonatomic,strong)UIView *popview;
@property(nonatomic,strong)UIScrollView *popScroView;
@property(assign)NSInteger checkIndex;
@property(assign)NSInteger times;
@property(nonatomic,strong)NSMutableArray *Model_arr;
@property(nonatomic,strong)NSDictionary *shareData;
#define psize 10
@end

@implementation Index_StaicViewController
-(UIView *)popview{
    if(!_popview){
        _popview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _popview.backgroundColor = RGBA(0, 0, 0, .8);
    }
    return _popview;
}
-(UIScrollView*)popScroView{
    if(!_popScroView){
        _popScroView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screen_width-0, screen_height)];
        _popScroView.backgroundColor = [UIColor whiteColor];
        _popScroView.pagingEnabled = 1;
        _popScroView.delegate = self;
        _popScroView.showsVerticalScrollIndicator = 0;
        [self.popview addSubview:_popScroView];
    }
    return _popScroView;
}
-(NSMutableArray *)Model_arr{
    if(!_Model_arr){
        _Model_arr = [NSMutableArray array];
    }
    return _Model_arr;
}
-(void)initSubViews{
    CGFloat height = KISIphoneX?44:20;
    self.popScroView.contentSize = CGSizeMake(0, screen_height*self.dataSouce.count);
    for(int i =0;i<self.dataSouce.count;i++){
        ShowDetail *view = [[ShowDetail alloc]initWithFrame:CGRectMake(0, screen_height*i, screen_width, screen_height)];
        [view setDic:self.dataSouce[i]];
        view.tag = i;
        view.enter_Btn.tag = i;
        [view.enter_Btn addTarget:self action:@selector(enter:) forControlEvents:UIControlEventTouchUpInside];
        view.sahre_Btn.tag = i+1024;
        [view.sahre_Btn addTarget:self action:@selector(shares:) forControlEvents:UIControlEventTouchUpInside];
        [view setModel:self.Model_arr[i]];
        [self.popScroView addSubview:view];
    }
}
#pragma mark 分享参数
-(void)ShareData{
    // http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=store&op=activity&m=bz_activities&token=194d7d75d1b6ac4ed794a53732af625e&ta=get_share_url
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"get_share_url"};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            self.shareData = response[@"data"];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)enter:(UIButton*)sender{
    [self hidepop];
    NSDictionary *dic = [self.dataSouce objectAtIndex:sender.tag];
    NSString *live_Id = [NSString stringWithFormat:@"%@",dic[@"activityid"]];
    NSString *roomNum = [NSString stringWithFormat:@"%@",dic[@"room_number"]];
    NSDictionary *paramter = @{@"op":@"address",@"ctrl":@"live",@"ac":@"member",@"ta":@"check_actroom_address",@"aid":live_Id};
    [self weqPostHandle:paramter success:^(id response) {
        if(response){
            C_PlayViewController *vc = [[C_PlayViewController alloc]init];
            vc.live_id = live_Id;
            vc.roomNum= roomNum;
            [self pushSecondVC:vc];
        }else{
            Regist2ViewController *vc = [[Regist2ViewController alloc]init];
            vc.live_id = live_Id;
            vc.roomNum = roomNum;
            [self pushSecondVC:vc];
        }
    } failure:^(NSError *error) {
        
    }];
//    Regist2ViewController *vc = [[Regist2ViewController alloc]init];
//    vc.live_id = [NSString stringWithFormat:@"%@",dic[@"activityid"]];
//    vc.roomNum = [NSString stringWithFormat:@"%@",dic[@"room_number"]];
//    [self pushSecondVC:vc];
}
-(void)shares:(UIButton *)sender{
   // [WToast showWithText:@"开发中"];
    NSDictionary *dic = [XTool GetDefaultInfo:USER_INFO];
    NSString *codes = [NSString stringWithFormat:@"%@&invite=%@",self.shareData[@"url"] ,dic[@"invite_code"]];
    NSString *kLinkURL = codes;
    NSString *kLinkTitle =self.shareData[@"title"];
    NSString *kLinkDescription =self.shareData[@"title"];
    //    NSString *kLinkTitle = self.live_Detail[@"prize_title"];
    //    NSString *kLinkDescription = self.live_Detail[@"prize_desc"];
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    // 是否是文档
    req1.bText =  NO;
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,
    req1.scene = WXSceneSession;
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = kLinkTitle;//分享标题
    urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"96.png"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = kLinkURL;//分享链接
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    //发送分享信息
    [WXApi sendReq:req1];
}

-(void)showpop{
    [self initSubViews];
    self.popview.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:self.popview];
    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
    
    self.popScroView.transform = CGAffineTransformScale(CGAffineTransformIdentity,0,0);
    // self.alertview.alpha = 0;
    [UIView animateWithDuration:0.3 delay:0.1 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:UIViewAnimationOptionCurveLinear animations:^{
        self.popview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.4f];
        self.popScroView.transform = transform;
        self.popScroView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   // [self stoptime];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
    if([XTool GetDefaultInfo:USER_INFO]){
    [self startTime];
    }
}
-(NSMutableArray *)dataSouce{
    if(!_dataSouce){
        _dataSouce = [NSMutableArray array];
    }
    return _dataSouce;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stoptime) name:STOPTIMENOTO object:nil];
    [self setViews];
    [self ShareData];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
    UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidepop)];
    [self.popview addGestureRecognizer:taps];
 //   [self initSubViews];

    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
  // self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self

   self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self

                                                                   refreshingAction:@selector(loadData)];
    [self.view bringSubviewToFront:self.tableView];
    self.search_Tf.delegate = self;
    self.keywords = @"";
    self.pageIndex = 1;
    [self loadData];
 //   [self startTime];
   //  [kCountDownManager start];

    [self fetchRollNews];
    // Do any additional setup after loading the view from its nib.
}

-(void)refresh{
    self.pageIndex = 1;
    [self.dataSouce removeAllObjects];
    [self.Model_arr removeAllObjects];
  //  [kCountDownManager removeAllSource];
    [self loadData];
}
-(void)hidepop{
    [UIView animateWithDuration:0.3 animations:^{
        [self.popview removeFromSuperview];
    }];
}
-(void)hideKb{
    [self.view endEditing:1];
}
-(void)stoptime{
    dispatch_cancel(self.Dm_timer);
    
}

-(void)startTime{
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
   [self loadStatic];
    self.times++;
        if(self.Model_arr.count>0){
        for(int i =0;i<self.Model_arr.count;i++){
            LiveModel *model = [self.Model_arr objectAtIndex:i];
            if(model.startcount>0){
                model.startcount--;
            }else{
                model.startcount=0;
            }
            model.count--;
            
            [self.Model_arr replaceObjectAtIndex:i
                                      withObject:model];
            
        }
           [[NSNotificationCenter defaultCenter] postNotificationName:TimeCellNotification object:nil];
        }
    });
   //4.开始执行
    dispatch_resume(timer);
    self.Dm_timer = timer;
}
-(void)loadStatic{
    if(![XTool GetDefaultInfo:USER_INFO]){
        return;
    }
    NSDictionary *param = @{@"ac":@"store",@"op":@"activity",@"ctrl":@"live",@"ta":@"index_total"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
         
            self.StaticshowDic = response[@"data"];
            self.total.text = [NSString stringWithFormat:@"今天全国：共%@场",response[@"data"][@"nationwide"]];
            self.now_Total.text =  [NSString stringWithFormat:@"正直播：%@场",response[@"data"][@"ong_actnum"]];
            self.people.text = [NSString stringWithFormat:@"总人数：%@",response[@"data"][@"man_actnum"]];
            self.areaNUm.text =  [NSString stringWithFormat:@"所在区域：总共%@场",response[@"data"][@"city_actnum"]];
            self.areanow_Num.text = [NSString stringWithFormat:@"正直播：%@场",response[@"data"][@"ong_cityactnum"]];
            self.areapeople.text =  [NSString stringWithFormat:@"总人数：%@",response[@"data"][@"man_cityactnum"]];
          //  [self.tableView reloadData];
            [self.Topcell bindData:response[@"data"]];
        }
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)loadData{
    if(![XTool GetDefaultInfo:USER_INFO]){
        return;
    }
    NSDictionary *param = @{@"ac":@"store",@"op":@"activity",@"ctrl":@"live",@"room_number":self.keywords,@"page":[NSString stringWithFormat:@"%ld",(long)self.pageIndex],@"psize":[NSString stringWithFormat:@"%d",psize]};
    [self weqPostHandle:param success:^(id response) {
         [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        if(response){
            self.pageIndex++;
            NSArray *acti_Arr = response[@"data"][@"list"];
            if(acti_Arr.count==0){
                [WToast showWithText:@"此时段暂无直播"];
            }else{
                [self.dataSouce addObjectsFromArray:response[@"data"][@"list"]];
                 self.now_time = [NSString stringWithFormat:@"%@",response[@"data"][@"service_time"]];
                NSInteger now_Time = [response[@"data"][@"service_time"]integerValue];
                for(int i =0;i<acti_Arr.count;i++){
                    NSDictionary *dic = acti_Arr[i];
                    
                    LiveModel *model = [[LiveModel alloc]init];
                    NSInteger counts = [dic[@"end_time"]integerValue]-now_Time;
                    NSInteger starttime =[dic[@"end_time"]integerValue]-now_Time;
                    model.count = counts;
                    model.startcount = [dic[@"start_time"]integerValue]-now_Time;
                    model.timeOut = 0;
                    model.countDownSource =  [NSString stringWithFormat:@"OYPagingSource%zd", self.pageIndex];
                    [self.Model_arr addObject:model];
                }
             //   [kCountDownManager addSourceWithIdentifier:[NSString stringWithFormat:@"OYPagingSource%zd", self.pageIndex]];
            }
          //  [kCountDownManager reload];
            [self.tableView reloadData];
            }else{
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    }];
}
//键盘的搜索事件
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:1];
    self.keywords = textField.text;
    [self.dataSouce removeAllObjects];
    [self loadData];
    
    return YES;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:1];
}

- (IBAction)filter:(UIButton *)sender {
    LiveCatogryViewController *vc = [[LiveCatogryViewController alloc]init];
    [self pushSecondVC:vc];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 1;
    }else
    return self.dataSouce.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        static NSString *CellId = @"cells";
        self.Topcell = [tableView dequeueReusableCellWithIdentifier:CellId];
        if(!self.Topcell){
            self.Topcell= [[[NSBundle mainBundle]loadNibNamed:@"Staic_TopCell" owner:self options:nil]lastObject];
        }
        self.Topcell.selectionStyle = UITableViewCellSelectionStyleNone;
       return self.Topcell;
    }
    else{
    static NSString *CellId = @"cell";
    Static_ShowCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if(!cell){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"Static_ShowCell" owner:self options:nil]lastObject];
    }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSInteger tiem_New = [self.now_time integerValue]+self.times;
        NSString *time_Str = [NSString stringWithFormat:@"%ld",tiem_New];
        cell.model = self.Model_arr[indexPath.row];
        [cell bindData:self.dataSouce[indexPath.row] andtime:time_Str];
        __weak typeof (self)weakSelf = self;
        cell.countDownZero=^(LiveModel * model){
           // LiveModel *models = self.Model_arr[indexPath.row];
             LiveModel *models = model;
            if(models.startcount>0){
                //未开始的状态
                 models.count = models.count-models.startcount;
                models.startcount = 0;
                NSLog(@"开始的倒计时结束");
                }else{
                //直播结束
                    
                models.count=0;
                models.timeOut = 1;
                NSLog(@"直播倒计时结束");
            }
             model.countDownSource =  [NSString stringWithFormat:@"OYPagingSource%zd", self.pageIndex];
            [self.Model_arr replaceObjectAtIndex:indexPath.row withObject:models];
            [weakSelf.tableView reloadData];
//            NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row inSection:1];
//            [weakSelf.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationRight];
          //  [kCountDownManager reload];
        };
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==1){
    [self showpop];
    [self initSubViews];
    self.checkIndex = indexPath.row;
    self.popScroView.contentOffset = CGPointMake(0, screen_height*indexPath.row);
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        return 215;
    }else{
    return 180;
    }
}
-(void)setViews{
    self.search_View.layer.cornerRadius = 22;
    self.search_View.layer.masksToBounds = 1;
    self.Static_View1.layer.cornerRadius = 42;
    self.Static_View1.layer.masksToBounds = 1;
    self.static_View2.layer.cornerRadius = 42;
    self.static_View2.layer.masksToBounds = 1;
    [self.search_Tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.oldTopHeight = self.topVIew.frame.size.height;
    self.oldTabHeight = self.tableView.frame.size.height;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)area:(UIButton *)sender {
    AreaViewController *vc = [[AreaViewController alloc]init];
    [self pushSecondVC:vc];
}





#pragma mark--
- (void)fetchRollNews
{
    /**
     http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=store&op=activity&m=bz_activities&token=194d7d75d1b6ac4ed794a53732af625e&ta=get_winning_prize
     
     */
    
    HelenParametersDic *dict = [HelenParametersDic h_dictionary];
    dict[@"ac"] = @"store";
    dict[@"ctrl"] = @"live";
    dict[@"op"] = @"activity";
    dict[@"ta"] = @"get_winning_prize";
    dict[@"token"] = [RZ_USERDEFAULTES objectForKey:USER_INFO][@"token"];
    
    [HelenHttpClient requestWithUrlString:BASE_URL andParam:dict andMethod:@"POST" progress:nil success:^(id responseObject) {
        
        NSDictionary *res = responseObject[@"message"];
        NSInteger code = [res[@"resultCode"] integerValue];
        if(code== 0 || code ==1){
            [self showRollViewWithNews:res[@"data"]];
        }
        
    } andFailBlock:^(NSInteger ErrorCode, NSError *ErrorString) {
        
    }];
}


- (void)showRollViewWithNews:(NSArray *)news
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableArray<NSString *> *items = [NSMutableArray array];
        [news enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *name = obj[@"nickname"];
            if(name.length >=1){
                name = [name substringToIndex:1];
            }
            NSString *des = obj[@"goods_title"];
            NSString *timeStr = [NSDate dateFormatterHMWithTimeStamp:[obj[@"goods_title"] doubleValue]];
            NSString *str = [NSString stringWithFormat:@"恭喜 %@* 于%@ 获得%@",name,timeStr,des];
            [items addObject:str];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            SPRollView *rollview = [SPRollView shareInstance];
            rollview.frame = CGRectMake(0, kTopHeight+10, RZ_SCREEN_WIDTH, 25);
            rollview.margin_item_x = 15;
            rollview.margin_firstItem_x = rollview.width;
            rollview.speed = 80;
            rollview.timeInterval = 1.0/60;
            rollview.msgArray = items;
            [rollview startAnimation];
            [self.view addSubview:rollview];
        });
    });
}


@end
